﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using static System.Collections.Specialized.BitVector32;

namespace 委托_事件
{
    #region 委托_事件
    public delegate void CatCallEventHandler();
    public class Cat
    {
        public event CatCallEventHandler CatCall;
        public void OnCatCall()
        {
            Console.WriteLine("猫叫了一声");
            CatCall?.Invoke();
        }
    }
    public class Mouse
    {
        //定义老鼠跑掉方法
        public void MouseRun()
        {
            Console.WriteLine("老鼠跑了");
        }
    }
    public class People
    {
        //定义主人醒来方法
        public void WakeUp()
        {
            Console.WriteLine("主人醒了");
        }
    }
    #endregion

    #region 委托更新对象
    public class Person
    {
        public int Id { get; set; }
        public int Age { get; set; }
        public string Name{ get; set; }
        public string Address { get; set; }

        /// <summary>
        /// 下一年要更新所有人的年龄
        /// </summary>
        public async Task<Dictionary<string, Person>> NextYear()
        {
            var persons = new Dictionary<string, Person>();
            await UpdateAge(persons, (a, b) => a.Age=b);
            await UpdateAddress(persons, (a, b) => a.Address=b);
            return persons;
        }
        public async Task UpdateAge(Dictionary<string, Person> persons, Action<Person, int> action)
        {
            await Task.Run(() =>
            {
                persons.Add("1", new Person {Id=1,Age=10,Address="123",Name="张三" });
                persons.Add("2", new Person {Id=2,Age=20,Address="123",Name= "李四" });
                foreach (var item in persons)
                {
                    action(item.Value, item.Value.Age+=1);
                }
            });
        }
        public async Task UpdateAddress(Dictionary<string, Person> persons, Action<Person, string> action)
        {
            await Task.Run(() =>
            {
                foreach (var item in persons)
                {
                    action(item.Value, item.Value.Address+="abc");
                }
            });
        }
    }
   
    class Program
    {
        #endregion
        static void Main(string[] args)
        {
            //Cat cat = new Cat();
            //Mouse mouse = new Mouse();
            //People people = new People();
            ////把方法当做参数传给一个委托，然后把委托赋值给一个事件
            //cat.CatCall += new CatCallEventHandler(mouse.MouseRun);
            //cat.CatCall += new CatCallEventHandler(people.WakeUp);
            //cat.OnCatCall();
            //Console.ReadKey();


            Person person = new Person();
            var list =  person.NextYear().Result;
            foreach (var item in list)
            {
                Console.WriteLine($"{item.Value.Name}:{item.Value.Age}:{item.Value.Address}");
            }
            Console.ReadKey();
        }
    }

}
